{% extends "pc/base.html" %}

{% block content %}
<!-- 统计页面 -->
<div class="d-flex justify-content-between align-items-center mb-4">
    <h5 class="mb-0">数据统计</h5>
    <div class="d-flex gap-2">
        <button class="btn-control btn-warning" id="complete-dau">
            <i class="bi bi-plus-circle"></i> 补全DAU
        </button>
        <button class="btn-control" id="refresh-statistics">
            <i class="bi bi-arrow-clockwise"></i> 刷新数据
        </button>
    </div>
</div>

<!-- 统计图表 -->
<div class="row mb-4">
    <div class="col-12">
        <div class="card">
            <div class="card-body">
                <h6 class="card-title">数据趋势图表 (最近30天)</h6>
                <div class="d-flex flex-wrap gap-2 mb-3">
                    <button class="btn btn-sm btn-outline-primary chart-toggle active" data-metric="messages_combined">消息数据</button>
                    <button class="btn btn-sm btn-outline-primary chart-toggle" data-metric="active_combined">活跃数据</button>
                    <button class="btn btn-sm btn-outline-success chart-toggle" data-metric="total_combined">用户数据</button>
                    <button class="btn btn-sm btn-outline-info chart-toggle" data-metric="group_events">群组变化</button>
                    <button class="btn btn-sm btn-outline-warning chart-toggle" data-metric="friend_events">好友变化</button>
                </div>
                <div class="chart-container position-relative">
                    <div id="chart-average-display" class="chart-average-display"></div>
                    <canvas id="statisticsChart" width="400" height="200"></canvas>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 日期选择器 -->
<div class="row mb-3 date-selector-container">
    <div class="col-12">
        <div class="card">
            <div class="card-body" style="padding-bottom: 20px; position: relative; z-index: 100;">
                <div class="d-flex align-items-center justify-content-between">
                    <div class="d-flex align-items-center gap-3">
                        <label for="date-selector" class="form-label mb-0">查看日期:</label>
                        <select class="form-select date-selector-dropdown" id="date-selector" style="width: 200px;">
                            <option value="today">今日数据</option>
                        </select>
                        <small class="text-muted">选择要查看的日期数据</small>
            </div>
                    <div id="data-source-info" class="data-source-info">
                        <span class="badge bg-secondary">
                            <i class="bi bi-hourglass-split"></i> 加载中...
                        </span>
        </div>
    </div>
            </div>
        </div>
    </div>
</div>

<!-- 详细数据表格 -->
<div class="row">
    <div class="col-md-6">
        <div class="card">
            <div class="card-body">
                <h6 class="card-title" id="stats-table-title">今日数据概览</h6>
                <div class="table-responsive">
                    <table class="table table-sm">
                        <tbody id="today-stats-table">
                            <tr><td colspan="2" class="text-center text-muted">加载中...</td></tr>
                        </tbody>
                    </table>
                </div>
                
                <!-- 指令使用排行放在今日数据下面 -->
                <hr class="my-3">
                <h6 class="card-title">指令使用排行</h6>
                <div class="table-responsive">
                    <table class="table table-sm">
                        <thead>
                            <tr>
                                <th>指令</th>
                                <th>使用次数</th>
                            </tr>
                        </thead>
                        <tbody id="command-stats-table">
                            <tr><td colspan="2" class="text-center text-muted">加载中...</td></tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
    <div class="col-md-6">
        <div class="card">
            <div class="card-body">
                <!-- 最活跃用户在上方 -->
                <h6 class="card-title">最活跃用户</h6>
                <div class="table-responsive">
                    <table class="table table-sm">
                        <thead>
                            <tr>
                                <th>用户ID</th>
                                <th>消息数</th>
                            </tr>
                        </thead>
                        <tbody id="top-users-table">
                            <tr><td colspan="2" class="text-center text-muted">加载中...</td></tr>
                        </tbody>
                    </table>
                </div>
                
                <!-- 最活跃群组在下方 -->
                <hr class="my-3">
                <h6 class="card-title">最活跃群组</h6>
                <div class="table-responsive">
                    <table class="table table-sm">
                        <thead>
                            <tr>
                                <th>群组ID</th>
                                <th>消息数</th>
                            </tr>
                        </thead>
                        <tbody id="top-groups-table">
                            <tr><td colspan="2" class="text-center text-muted">加载中...</td></tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_styles %}
<style>
.chart-container {
    height: 400px !important;
    position: relative;
}

.chart-average-display {
    position: absolute;
    top: 10px;
    right: 10px;
    background: rgba(255, 255, 255, 0.9);
    padding: 4px 8px;
    border-radius: 4px;
    font-size: 12px;
    z-index: 10;
    box-shadow: 0 1px 3px rgba(0,0,0,0.1);
}

/* 响应式调整 */
@media (max-width: 768px) {
    .chart-container {
        height: 300px !important;
    }
    
    .d-flex.flex-wrap.gap-2.mb-3 {
        gap: 0.5rem !important;
    }
    
    .btn-sm {
        font-size: 0.8rem;
        padding: 0.25rem 0.5rem;
    }
}
</style>
{% endblock %}

{% block scripts %}
<script>
let statisticsChart = null;
let statisticsData = null;

const averageDisplayPlugin = {
    id: 'averageDisplay',
    afterDraw: function(chart) {
        const options = chart.options.plugins.averageDisplay;
        if (!options || !options.display) return;
        
        const ctx = chart.ctx;
        const legend = chart.legend;
        
        if (!legend || !legend.legendItems || legend.legendItems.length === 0) return;
        
        ctx.save();
        ctx.font = 'normal 12px Arial';
        ctx.fillStyle = options.color || '#666';
        ctx.textAlign = 'left';
        ctx.textBaseline = 'middle';
        
        const text = ` (${options.text})`;
        
        const legendItem = legend.legendItems[0];
        if (legendItem) {
            const labelWidth = ctx.measureText(legendItem.text).width;
            const x = legend.left + 35 + labelWidth;
            const y = legend.top + legend.height / 2;
            
            ctx.fillText(text, x, y);
        }
        
        ctx.restore();
    }
};

function debounce(func, delay) {
    let timeoutId;
    return function (...args) {
        clearTimeout(timeoutId);
        timeoutId = setTimeout(() => func.apply(this, args), delay);
    };
}

function formatNumber(num) {
    if (num === null || num === undefined) return '0';
    if (typeof num === 'object') {
        num = num.value ?? num.count ?? 0;
    }
    const numValue = Number(num);
    if (isNaN(numValue)) return '0';
    if (numValue >= 10000) return (numValue / 10000).toFixed(2).replace(/\.?0+$/, '') + 'w';
    if (numValue >= 1000) return (numValue / 1000).toFixed(2).replace(/\.?0+$/, '') + 'k';
    return numValue.toString();
}

function getStatValue(data, path, defaultValue = 0) {
    return data?.[path.split('.')[0]]?.[path.split('.')[1]] || defaultValue;
}

function getStat(item, statType, field) {
    return item?.[statType]?.[field] || 0;
}

function extractDataArrays(data, fields, statType = 'message_stats') {
    const arrays = fields.map(() => []);
    
    if (data.historical && Array.isArray(data.historical)) {
        data.historical.forEach(item => {
            fields.forEach((field, i) => {
                const value = typeof field === 'function' ? field(item) : getStat(item, statType, field);
                arrays[i].push(value);
            });
        });
    }
    
    if (data.today) {
        fields.forEach((field, i) => {
            const value = typeof field === 'function' ? field(data.today) : getStat(data.today, statType, field);
            arrays[i].push(value);
        });
    }
    
    return arrays;
}

function createDataset(label, data, color, bgColor) {
    return {
        label,
        data,
        borderColor: color,
        backgroundColor: bgColor,
        tension: 0.4,
        fill: false,
        pointRadius: 4,
        pointHoverRadius: 6
    };
}

const EMPTY_TABLE_ROW = '<tr><td colspan="2" class="text-center text-muted">暂无数据</td></tr>';

function getToken() {
    const urlParams = new URLSearchParams(window.location.search);
    return urlParams.get('token');
}

function initStatistics() {
    const ctx = document.getElementById('statisticsChart');
    if (!ctx) return;
    
    statisticsChart = new Chart(ctx.getContext('2d'), {
        type: 'line',
        data: {
            labels: [],
            datasets: [{
                label: '总消息量',
                data: [],
                borderColor: '#4361ee',
                backgroundColor: 'rgba(67, 97, 238, 0.15)',
                tension: 0.3,
                fill: false,
                pointRadius: 4,
                pointHoverRadius: 6
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            interaction: {
                intersect: false,
                mode: 'index'
            },
                    plugins: {
            legend: {
                display: true,
                position: 'top',
                align: 'start'
            },
            datalabels: {
                display: true,
                align: 'top',
                anchor: 'end',
                color: 'rgba(0, 0, 0, 0.6)',
                font: {
                    size: 10,
                    weight: 'normal'
                },
                formatter: function(value, context) {
                    return formatNumber(value);
                },
                padding: {
                    bottom: 4
                },
                clip: false
            },
            averageDisplay: {
                display: false
            }
        },
            scales: {
                x: {
                    display: true,
                    title: {
                        display: true,
                        text: '日期'
                    }
                },
                y: {
                    display: true,
                    title: {
                        display: true,
                        text: '数量'
                    },
                    beginAtZero: true
                }
            }
        },
        plugins: [ChartDataLabels, averageDisplayPlugin]
    });
}

function loadStatistics(forceRefresh = false) {
    const token = getToken();
    if (!token) {
        console.error('未找到访问token');
        return;
    }
    
    updateDataSourceInfo({
        data_source_info: {
            source: 'loading',
            update_time: '加载中...'
        }
    });
    
    let apiUrl = `/web/api/statistics?token=${encodeURIComponent(token)}&async=true`;
    if (forceRefresh) {
        apiUrl += '&force_refresh=true';
    }
    
    fetch(apiUrl)
        .then(response => {
            if (!response.ok) {
                throw new Error(`HTTP ${response.status}: ${response.statusText}`);
            }
            return response.json();
        })
        .then(data => {
            if (data.success) {
                if (data.task_id && data.status === 'started') {
                    pollTaskStatus(data.task_id, token);
                } else {
                    handleStatisticsData(data);
                }
            } else {
                console.error('加载统计数据失败:', data.error);
                showStatisticsError('加载统计数据失败: ' + (data.error || '未知错误'));
            }
        })
        .catch(error => {
            console.error('获取统计数据时出错:', error);
            showStatisticsError('获取统计数据时出错: ' + error.message);
        });
}

function pollTaskStatus(taskId, token, maxAttempts = 60) {
    let attempts = 0;
    
    const checkStatus = () => {
        attempts++;
        if (attempts > maxAttempts) {
            showStatisticsError('统计任务超时，请稍后重试');
            return;
        }
        
        fetch(`/web/api/statistics/task/${taskId}?token=${encodeURIComponent(token)}`)
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    const taskData = data;
                    
                    if (taskData.progress !== undefined) {
                        updateDataSourceInfo({
                            data_source_info: {
                                source: 'processing',
                                update_time: `${taskData.message || '处理中'} (${taskData.progress}%)`
                            }
                        });
                    }
                    
                    if (taskData.status === 'completed') {
                        if (taskData.data) {
                            handleStatisticsData(taskData.data);
                        } else {
                            showStatisticsError('统计任务完成但无数据返回');
                        }
                    } else if (taskData.status === 'failed') {
                        showStatisticsError('统计任务失败: ' + (taskData.error || '未知错误'));
                    } else {
                        setTimeout(checkStatus, 1000);
                    }
                } else {
                    showStatisticsError('查询任务状态失败: ' + (data.error || '未知错误'));
                }
            })
            .catch(error => {
                console.error('查询任务状态出错:', error);
                showStatisticsError('查询任务状态出错: ' + error.message);
            });
    };
    
    setTimeout(checkStatus, 1000);
}

function handleStatisticsData(data) {
    statisticsData = data;
    
    if (data.data_source_info) {
        updateDataSourceInfo(data);
    }
    
    if (data.historical && data.today) {
        updateChart('messages_combined');
        updateTables(data.today || {});
    } else if (data.selected_date_data) {
        updateTables(data.selected_date_data);
    }
}

function updateChart(metric) {
    if (!statisticsChart || !statisticsData) return;
    
    const labels = [];
    const data = [];
    let total = 0;
    let count = 0;
    
    if (statisticsData.historical && Array.isArray(statisticsData.historical)) {
        statisticsData.historical.forEach(item => {
            const displayLabel = item.display_date || item.date || '未知';
            labels.push(displayLabel);
            
            let value = 0;
            switch(metric) {
                case 'total_messages':
                case 'active_users':
                case 'active_groups':
                case 'private_messages':
                    value = item.message_stats ? item.message_stats[metric] || 0 : 0;
                    break;
                case 'total_users':
                case 'total_groups':
                case 'total_friends':
                    value = item.user_stats ? item.user_stats[metric] || 0 : 0;
                    break;
                default:
                    value = 0;
            }
            
        data.push(value);
        total += value;
        count++;
    });
    }
    
    if (statisticsData.today) {
        labels.push('今日');
        
        let todayValue = 0;
        switch(metric) {
            case 'total_messages':
            case 'active_users':
            case 'active_groups':
            case 'private_messages':
                todayValue = statisticsData.today.message_stats ? statisticsData.today.message_stats[metric] || 0 : 0;
                break;
            case 'total_users':
            case 'total_groups':
            case 'total_friends':
                todayValue = statisticsData.today.user_stats ? statisticsData.today.user_stats[metric] || 0 : 0;
                break;
            default:
                todayValue = 0;
        }
        
        data.push(todayValue);
        total += todayValue;
        count++;
    }
    
    let datasets = [];
    
    if (metric === 'messages_combined') {
        const [totalMessagesData, privateMessagesData, groupMessagesData] = extractDataArrays(
            statisticsData,
            ['total_messages', 'private_messages', item => getStat(item, 'message_stats', 'total_messages') - getStat(item, 'message_stats', 'private_messages')]
        );
        
        datasets = [
            createDataset('总消息量', totalMessagesData, '#4361ee', 'rgba(67, 97, 238, 0.15)'),
            createDataset('私聊消息数', privateMessagesData, '#7209b7', 'rgba(114, 9, 183, 0.15)'),
            createDataset('群聊消息数', groupMessagesData, '#f72585', 'rgba(247, 37, 133, 0.15)')
        ];
    } else if (metric === 'active_combined') {
        const [activeUsersData, activeGroupsData] = extractDataArrays(statisticsData, ['active_users', 'active_groups']);
        
        datasets = [
            createDataset('活跃用户数', activeUsersData, '#f72585', 'rgba(247, 37, 133, 0.15)'),
            createDataset('活跃群聊数', activeGroupsData, '#4cc9f0', 'rgba(76, 201, 240, 0.15)')
        ];
    } else if (metric === 'total_combined') {
        const [totalUsersData, totalGroupsData, totalFriendsData] = extractDataArrays(
            statisticsData, 
            ['total_users', 'total_groups', 'total_friends'], 
            'user_stats'
        );
        
        datasets = [
            createDataset('总用户数', totalUsersData, '#f77f00', 'rgba(247, 127, 0, 0.15)'),
            createDataset('总群组数', totalGroupsData, '#fcbf49', 'rgba(252, 191, 73, 0.15)'),
            createDataset('总好友数', totalFriendsData, '#606c38', 'rgba(96, 108, 56, 0.15)')
        ];
    } else if (metric === 'group_events') {
        const [joinData, leaveData] = extractDataArrays(
            statisticsData, 
            ['group_join_count', 'group_leave_count'], 
            'event_stats'
        );
        
        datasets = [
            createDataset('进群数', joinData, '#28a745', 'rgba(40, 167, 69, 0.15)'),
            createDataset('退群数', leaveData, '#dc3545', 'rgba(220, 53, 69, 0.15)')
        ];
    } else if (metric === 'friend_events') {
        const [addData, removeData] = extractDataArrays(
            statisticsData, 
            ['friend_add_count', 'friend_remove_count'], 
            'event_stats'
        );
        
        datasets = [
            createDataset('加好友数', addData, '#17a2b8', 'rgba(23, 162, 184, 0.15)'),
            createDataset('删好友数', removeData, '#ffc107', 'rgba(255, 193, 7, 0.15)')
        ];
    } else {
        const average = count > 0 ? (total / count) : 0;
        
        const metricInfo = {
            'total_messages': { label: '总消息量', color: '#4361ee', bg: 'rgba(67, 97, 238, 0.15)' },
            'active_users': { label: '活跃用户数', color: '#f72585', bg: 'rgba(247, 37, 133, 0.15)' },
            'active_groups': { label: '活跃群聊数', color: '#4cc9f0', bg: 'rgba(76, 201, 240, 0.15)' },
            'private_messages': { label: '私聊消息数', color: '#7209b7', bg: 'rgba(114, 9, 183, 0.15)' },
            'total_users': { label: '总用户数', color: '#f77f00', bg: 'rgba(247, 127, 0, 0.15)' },
            'total_groups': { label: '总群组数', color: '#fcbf49', bg: 'rgba(252, 191, 73, 0.15)' },
            'total_friends': { label: '总好友数', color: '#606c38', bg: 'rgba(96, 108, 56, 0.15)' }
        };
        
        const info = metricInfo[metric] || metricInfo['total_messages'];
        datasets = [createDataset(info.label, data, info.color, info.bg)];
        
        const averageElement = document.getElementById('chart-average-display');
        if (averageElement && count > 0) {
            averageElement.textContent = `30天平均: ${formatNumber(Math.round(average))}`;
            averageElement.style.color = info.color;
            averageElement.style.display = 'block';
        }
    }
    
    statisticsChart.data.labels = labels;
    statisticsChart.data.datasets = datasets;
    
    if (metric === 'messages_combined' || metric === 'active_combined' || metric === 'total_combined' || 
        metric === 'group_events' || metric === 'friend_events') {
        const averageElement = document.getElementById('chart-average-display');
        if (averageElement) {
            averageElement.style.display = 'none';
        }
    }
    
    statisticsChart.update();
    updateButtonState(metric);
}

function updateDataSourceInfo(data) {
    const infoElement = document.getElementById('data-source-info');
    if (!infoElement || !data.data_source_info) return;
    
    const sourceMap = {
        loading: { badge: 'bg-warning', icon: 'hourglass-split', text: '加载中' },
        processing: { badge: 'bg-info', icon: 'gear-fill', text: '计算中' },
        api: { badge: 'bg-success', icon: 'cloud-check', text: '实时数据' },
        cache: { badge: 'bg-info', icon: 'clock-history', text: '缓存数据' }
    };
    
    const sourceInfo = data.data_source_info;
    const { badge = 'bg-secondary', icon = 'hourglass-split', text = '未知' } = sourceMap[sourceInfo.source] || {};
    
    infoElement.innerHTML = `
        <span class="badge ${badge}">
            <i class="bi bi-${icon}"></i> ${text}
        </span>
        <small>${sourceInfo.update_time || ''}</small>
    `;
}

function populateDateSelector(dates) {
    const selector = document.getElementById('date-selector');
    selector.innerHTML = '';
    
    dates.forEach(dateItem => {
        const option = document.createElement('option');
        option.value = dateItem.value;
        option.textContent = dateItem.display;
        if (dateItem.is_today) {
            option.selected = true;
        }
        selector.appendChild(option);
    });
}

function loadAvailableDates() {
    const token = getToken();
    if (!token) return;
    
    fetch(`/web/api/available_dates?token=${encodeURIComponent(token)}`)
        .then(response => response.json())
        .then(data => {
            if (data.success && data.dates) {
                populateDateSelector(data.dates);
            }
        })
        .catch(error => {
            console.error('Error loading available dates:', error);
        });
}

function loadDateData(date) {
    loadDateSpecificData(date);
}

function updateTodayStats(data) {
    const table = document.getElementById('today-stats-table');
    if (!data) {
        table.innerHTML = '<tr><td colspan="2" class="text-center text-muted">暂无数据</td></tr>';
        return;
    }
    
    const statsItems = [
        { label: '总消息量', value: data.total_messages || 0 },
        { label: '活跃用户数', value: data.active_users || 0 },
        { label: '活跃群聊数', value: data.active_groups || 0 },
        { label: '私聊消息数', value: data.private_messages || 0 },
        { label: '群聊消息数', value: data.group_messages || 0 },
        { label: '总用户数', value: data.total_users || 0 },
        { label: '总群组数', value: data.total_groups || 0 },
        { label: '总好友数', value: data.total_friends || 0 }
    ];
    
    table.innerHTML = statsItems.map(item => 
        `<tr><td>${item.label}</td><td class="fw-bold">${formatNumber(item.value)}</td></tr>`
    ).join('');
}

function updateTable(tableId, items, rowMapper) {
    const table = document.getElementById(tableId);
    if (!items || items.length === 0) {
        table.innerHTML = EMPTY_TABLE_ROW;
        return;
    }
    table.innerHTML = items.map(rowMapper).join('');
}

function updateTopUsers(users) {
    updateTable('top-users-table', users, user => 
        `<tr><td>${user.user_id}</td><td class="fw-bold">${formatNumber(user.message_count)}</td></tr>`
    );
}

function updateTopGroups(groups) {
    updateTable('top-groups-table', groups, group => 
        `<tr><td>${group.group_id}</td><td class="fw-bold">${formatNumber(group.message_count)}</td></tr>`
    );
}

function updateCommandStats(commands) {
    updateTable('command-stats-table', commands, cmd => 
        `<tr><td>${cmd.command}</td><td class="fw-bold">${formatNumber(cmd.count)}</td></tr>`
    );
}

function completeDau() {
    const token = getToken();
    if (!token) return;
    
    const button = document.getElementById('complete-dau');
    const originalText = button.innerHTML;
    button.innerHTML = '<i class="bi bi-hourglass-split"></i> 处理中...';
    button.disabled = true;
    
    fetch(`/web/api/complete_dau?token=${encodeURIComponent(token)}`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({})
    })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                alert('DAU补全成功！');
                loadStatistics();
            } else {
                alert('DAU补全失败：' + data.message);
            }
        })
        .catch(error => {
            console.error('Error completing DAU:', error);
            alert('DAU补全失败');
        })
        .finally(() => {
            button.innerHTML = originalText;
            button.disabled = false;
        });
}

function showStatisticsError(message) {
    const container = document.getElementById('statistics-container');
    if (container) {
        container.innerHTML = `
            <div class="alert alert-danger">
                <i class="bi bi-exclamation-triangle"></i> ${message}
            </div>
        `;
    }
}

function updateButtonState(metric) {
    document.querySelectorAll('.chart-toggle').forEach(btn => {
        btn.classList.remove('active');
        if (btn.dataset.metric === metric) {
            btn.classList.add('active');
        }
    });
}

function updateTables(todayData) {
    const todayStatsTable = document.getElementById('today-stats-table');
    const messageStats = todayData.message_stats || {};
    const userStats = todayData.user_stats || {};
    
    const dataSourceInfoElement = document.getElementById('data-source-info');
    if (dataSourceInfoElement) {
        let sourceHtml = '';
        if (todayData.is_historical) {
            sourceHtml = `<span class="badge bg-info">
                <i class="bi bi-folder"></i> 本地文件
            </span>`;
            if (todayData.generated_at) {
                try {
                    const genTime = new Date(todayData.generated_at);
                    const timeStr = genTime.toLocaleString('zh-CN', { 
                        month: '2-digit', 
                        day: '2-digit', 
                        hour: '2-digit', 
                        minute: '2-digit' 
                    });
                    sourceHtml += `<br><small class="text-muted">
                        <i class="bi bi-clock"></i> ${timeStr}
                    </small>`;
                } catch (e) {
                    // 时间解析失败，忽略
                }
            }
        } else if (todayData.is_realtime) {
            sourceHtml = `<span class="badge bg-warning text-dark">
                <i class="bi bi-database"></i> 实时查询
            </span>`;
        } else {
            sourceHtml = `<span class="badge bg-success">
                <i class="bi bi-folder"></i> 本地文件
            </span>`;
        }
        dataSourceInfoElement.innerHTML = sourceHtml;
    }

    if (todayStatsTable) {
        const eventStats = todayData.event_stats || {};
        todayStatsTable.innerHTML = `
            <tr><td>总消息量</td><td>${messageStats.total_messages || 0}</td></tr>
            <tr><td>活跃用户数</td><td>${messageStats.active_users || 0}</td></tr>
            <tr><td>活跃群聊数</td><td>${messageStats.active_groups || 0}</td></tr>
            <tr><td>私聊消息数</td><td>${messageStats.private_messages || 0}</td></tr>
            <tr><td>最活跃时段</td><td>${messageStats.peak_hour || 0}点 (${messageStats.peak_hour_count || 0}条)</td></tr>
            <tr><td>总用户数</td><td>${userStats.total_users || 0}</td></tr>
            <tr><td>总群组数</td><td>${userStats.total_groups || 0}</td></tr>
            <tr><td>总好友数</td><td>${userStats.total_friends || 0}</td></tr>
            <tr><td colspan="2" style="font-weight: bold; background-color: #f8f9fa;">事件统计</td></tr>
            <tr><td>进群数</td><td>${eventStats.group_join_count || 0}</td></tr>
            <tr><td>退群数</td><td>${eventStats.group_leave_count || 0}</td></tr>
            <tr><td>群组净增量</td><td>${(eventStats.group_join_count || 0) - (eventStats.group_leave_count || 0)}</td></tr>
            <tr><td>加好友数</td><td>${eventStats.friend_add_count || 0}</td></tr>
            <tr><td>删好友数</td><td>${eventStats.friend_remove_count || 0}</td></tr>
            <tr><td>好友净增量</td><td>${(eventStats.friend_add_count || 0) - (eventStats.friend_remove_count || 0)}</td></tr>
        `;
    }
    
    const topGroups = messageStats.top_groups || [];
    updateTable('top-groups-table', topGroups.slice(0, 5), group => 
        `<tr><td>${maskId(group.group_id)}</td><td>${group.message_count}</td></tr>`
    );
    
    const topUsers = messageStats.top_users || [];
    if (topUsers.length > 0) {
        updateTable('top-users-table', topUsers.slice(0, 5), user => 
            `<tr><td><span class="user-id-with-nickname" data-user-id="${user.user_id}">${maskId(user.user_id)} <span class="nickname-loading">📝</span></span></td><td>${user.message_count}</td></tr>`
        );
        loadNicknamesForUsers(topUsers.slice(0, 5));
    } else {
        document.getElementById('top-users-table').innerHTML = EMPTY_TABLE_ROW;
    }
    
    const commandStats = todayData.command_stats || [];
    updateTable('command-stats-table', commandStats.slice(0, 5), cmd => 
        `<tr><td>${cmd.command}</td><td>${cmd.count}</td></tr>`
    );
}

function maskId(id) {
    if (!id || typeof id !== 'string') return '未知';
    if (id.length <= 6) return id;
    return id.substring(0, 3) + '***' + id.substring(id.length - 3);
}

const nicknameCache = new Map();

function loadNicknamesForUsers(users) {
    users.forEach(user => {
        if (user.user_id && !nicknameCache.has(user.user_id)) {
            fetchUserNickname(user.user_id);
        } else if (nicknameCache.has(user.user_id)) {
            updateUserNickname(user.user_id, nicknameCache.get(user.user_id));
        }
    });
}

function fetchUserNickname(userId) {
    const token = getToken();
    if (!token) return;
    
    fetch(`/web/api/get_nickname/${encodeURIComponent(userId)}?token=${encodeURIComponent(token)}`)
        .then(response => response.json())
        .then(data => {
            if (data.success && data.nickname) {
                nicknameCache.set(userId, data.nickname);
                updateUserNickname(userId, data.nickname);
            }
        })
        .catch(error => {
            console.error('获取昵称失败:', error);
        });
}

function updateUserNickname(userId, nickname) {
    const elements = document.querySelectorAll(`[data-user-id="${userId}"]`);
    elements.forEach(element => {
        const loadingEl = element.querySelector('.nickname-loading');
        if (loadingEl) {
            loadingEl.textContent = `(${nickname})`;
            loadingEl.classList.remove('nickname-loading');
            loadingEl.classList.add('nickname-display');
        }
    });
}

function loadDateSpecificData(selectedDate) {
    if (selectedDate === 'today') {
        loadStatisticsData();
    } else {
        loadHistoricalDateData(selectedDate);
    }
}

function loadStatisticsData(forceRefresh = false) {
    loadStatistics(forceRefresh);
}

function loadHistoricalDateData(dateStr) {
    const token = getToken();
    if (!token) {
        console.error('未找到访问token');
        return;
    }
    
    updateDataSourceInfo({
        data_source_info: {
            source: 'loading',
            update_time: '加载历史数据...'
        }
    });
    
    const apiUrl = `/web/api/statistics?token=${encodeURIComponent(token)}&date=${dateStr}&async=false`;
    
    fetch(apiUrl)
        .then(response => {
            if (!response.ok) {
                throw new Error(`HTTP ${response.status}: ${response.statusText}`);
            }
            return response.json();
        })
        .then(data => {
            if (data.success) {
                if (data.selected_date_data) {
                    updateTables(data.selected_date_data);
                } else {
                    showStatisticsError('该日期没有可用数据');
                }
            } else {
                console.error('加载历史数据失败:', data.error);
                showStatisticsError('加载历史数据失败: ' + (data.error || '未知错误'));
            }
        })
        .catch(error => {
            console.error('获取历史数据时出错:', error);
            showStatisticsError('获取历史数据时出错: ' + error.message);
        });
}

document.addEventListener('DOMContentLoaded', function() {
    const initTasks = [
        { fn: initStatistics, delay: 50 },
        { fn: loadStatistics, delay: 100 },
        { fn: loadAvailableDates, delay: 150 }
    ];
    
    const events = [
        { selector: '.chart-toggle', event: 'click', handler: (e) => updateChart(e.target.dataset.metric), debounce: 200 },
        { selector: '#refresh-statistics', event: 'click', handler: () => {
            loadStatistics();
            loadDateSpecificData(document.getElementById('date-selector').value);
        }, debounce: 1000 },
        { selector: '#complete-dau', event: 'click', handler: completeDau, debounce: 500 },
        { selector: '#date-selector', event: 'change', handler: (e) => loadDateSpecificData(e.target.value), debounce: 300 }
    ];
    
    events.forEach(({ selector, event, handler, debounce: delay }) => {
        const debouncedHandler = delay ? debounce(handler, delay) : handler;
        const elements = document.querySelectorAll(selector);
        elements.forEach(el => el.addEventListener(event, debouncedHandler));
    });
    
    const initAsync = () => initTasks.forEach(({ fn, delay }) => setTimeout(fn, delay));
    
    ('requestIdleCallback' in window) 
        ? requestIdleCallback(initAsync, { timeout: 300 })
        : setTimeout(initAsync, 100);
});
</script>
{% endblock %}